import React, { Component } from "react";
import {
  ActivityIndicator,
  View,
  Dimensions,
  Animated,
  Image,
  Text,
  Alert,
  Platform,
} from "react-native";

const { width, height } = Dimensions.get("window");

// 定义 Toast 类型
type ToastType = "success" | "error" | "warning" | "default" | "loading";
// 定义位置类型
type PositionType = "top" | "center" | "bottom";

// 定义图标路径
const iconPaths: Record<ToastType, string> = {
  success: require("@/assets/images/tabbar/chenggong.png"),
  error: require("@/assets/images/tabbar/shibai.png"),
  warning: require("@/assets/images/tabbar/zhuyi.png"),
  default: "",
  loading: "",
};

// 定义 AddToast 组件的 props 类型
interface AddToastProps {
  delete: (res: any) => void;
  children: React.ReactNode;
  type: ToastType;
  duration?: number;
}

// 定义 AddToast 组件的 state 类型
interface AddToastState {
  fadeAnim: Animated.Value;
}

class AddToast extends Component<AddToastProps, AddToastState> {
  constructor(props: AddToastProps) {
    super(props);
    this.state = {
      fadeAnim: new Animated.Value(0),
    };
  }

  componentDidMount() {
    const duration = this.props.duration || 3000;
    if (duration === -1) {
      // 如果 duration 为 -1，则只进行淡入动画，不进行淡出动画
      Animated.timing(this.state.fadeAnim, {
        toValue: 1,
        duration: 500,
        useNativeDriver: true,
      }).start();
    } else {
      Animated.sequence([
        Animated.timing(this.state.fadeAnim, {
          toValue: 1,
          duration: 500,
          useNativeDriver: true,
        }),
        Animated.delay(duration),
        Animated.timing(this.state.fadeAnim, {
          toValue: 0,
          duration: 500,
          useNativeDriver: true,
        }),
      ]).start((res) => {
        this.props.delete && this.props.delete(res);
      });
    }
  }

  render() {
    const { fadeAnim } = this.state;
    const opacity = fadeAnim.interpolate({
      inputRange: [0, 1],
      outputRange: [0, 1],
    });
    const translateY = fadeAnim.interpolate({
      inputRange: [0, 1],
      outputRange: [20, 0],
    });

    const iconPath = iconPaths[this.props.type];

    return (
      <Animated.View
        style={{
          opacity,
          borderRadius: 10,
          paddingVertical: 10,
          paddingHorizontal: 10,
          transform: [{ translateY }],
          backgroundColor: "#2c2c2c",
          alignItems: "center",
          justifyContent: "center",
          flexDirection: "column",
          zIndex: 1000,
          maxWidth: 300,
        }}
      >
        {this.props.type === "loading" ? (
          <ActivityIndicator
            size={30}
            color="#FFFFFF"
            style={{ marginBottom: 5 }}
          />
        ) : iconPath ? (
          <Image
            source={iconPath as any}
            style={{ width: 30, height: 30, marginBottom: 10 }}
          />
        ) : null}

        <Text style={{ color: "#fff", fontSize: 18 }}>
          {this.props.children}
        </Text>
      </Animated.View>
    );
  }
}

// 定义 ToastView 组件的 props 类型
interface ToastViewProps {
  // 可以根据需要添加更多 props
}

// 定义 ToastView 组件的 state 类型
interface ToastViewState {
  toastList: {
    text: string;
    value: React.ReactNode;
    type: ToastType;
    position: PositionType;
    duration?: number;
  }[];
}

let toastInstance: ToastView | null = null;

class ToastView extends Component<ToastViewProps, ToastViewState> {
  private key = 0;

  constructor(props: ToastViewProps) {
    super(props);
    this.state = {
      toastList: [],
    };
    this.deleteToast = this.deleteToast.bind(this);
    toastInstance = this;
  }

  static add = (
    value: string,
    type: ToastType = "default",
    position: PositionType = "center",
    duration?: number
  ) => {
    if (toastInstance) {
      const { toastList } = toastInstance.state;
      const toastAddState = !toastList.some((item) => item.text === value);

      if (toastAddState) {
        const newToast = {
          text: value,
          value: (
            <AddToast
              key={toastInstance.key}
              delete={toastInstance.deleteToast}
              type={type}
              duration={duration}
            >
              {value}
            </AddToast>
          ),
          type,
          position,
          duration,
        };
        toastInstance.key++;
        toastInstance.setState((prevState) => ({
          toastList: [...prevState.toastList, newToast],
        }));
        toastInstance.forceUpdate();
      }
    }
  };

  static success = (
    value: string,
    position: PositionType = "center",
    duration?: number
  ) => {
    ToastView.add(value, "success", position, duration);
  };

  static error = (
    value: string,
    position: PositionType = "center",
    duration?: number
  ) => {
    ToastView.add(value, "error", position, duration);
  };

  static warning = (
    value: string,
    position: PositionType = "center",
    duration?: number
  ) => {
    ToastView.add(value, "warning", position, duration);
  };

  static loading = (
    value: string,
    position: PositionType = "center",
    duration?: number
  ) => {
    ToastView.add(value, "loading", position, duration);
  };

  deleteToast() {
    this.setState((prevState) => ({
      toastList: prevState.toastList.slice(1),
    }));
  }

  static close = () => {
    if (toastInstance) {
      toastInstance.deleteToast();
    }
  };

  render() {
    // 取第一个 Toast 的位置作为当前的位置
    const position =
      this.state.toastList.length > 0
        ? this.state.toastList[0].position
        : "bottom";
    let style = {
      position: "absolute",
      left: 0,
      width,
      justifyContent: "center",
      alignItems: "center",
    };

    switch (position) {
      case "top":
        style = { ...style, top: 50 } as any;
        break;
      case "center":
        style = { ...style, top: height / 2 } as any;
        break;
      case "bottom":
        style = { ...style, bottom: 50 } as any;
        break;
    }

    return (
      <View style={style as any}>
        {this.state.toastList.map((item) => item.value)}
      </View>
    );
  }
}

// 创建 ToastAPI 单例对象
const ToastAPI = {
  show: (
    value: string,
    type: ToastType = "default",
    position: PositionType = "center",
    duration?: number
  ) => {
    ToastView.add(value, type, position, duration);
  },
  success: (
    value: string,
    position: PositionType = "center",
    duration?: number
  ) => {
    ToastView.success(value, position, duration);
  },
  error: (
    value: string,
    position: PositionType = "center",
    duration?: number
  ) => {
    Platform.OS === "ios"
      ? Alert.alert("提示", value)
      : ToastView.error(value, position, duration);
  },
  loading: (
    value: string,
    position: PositionType = "center",
    duration?: number
  ) => {
    ToastView.loading(value, position, duration);
  },
  warning: (
    value: string,
    position: PositionType = "center",
    duration?: number
  ) => {
    Platform.OS === "ios"
      ? Alert.alert("提示", value)
      : ToastView.warning(value, position, duration);
  },
  close: () => {
    ToastView.close();
  },
};
const withToast = (WrappedComponent: React.ComponentType<any>) => {
  return class extends React.Component {
    render() {
      return (
        <>
          <WrappedComponent {...this.props} />
          <ToastView />
        </>
      );
    }
  };
};

// 导出高阶组件和 ToastAPI
export { withToast, ToastAPI };
